<?php

namespace App\Http\Controllers\V1;

use Throwable;
use App\Support\Code;
use App\Support\Config;
use App\Models\Exchange;
use App\Support\Currency;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\ExchangeCollection;

class ExchangeController extends ApiController
{
    /**
     * 兑换页面
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ConfigNotSetException
     */
    public function show()
    {
        $configs = Config::getExchanges();

        $data = [];
        foreach ($configs as $key => $config) {
            $data[$key . '_RMB'] = [
                'to' => $config['second_rmb'],
                'from' => $config['first_rmb']
            ];
        }

        $from = [
            [
                'unit' => 'rmb',
                'currency' => 'YEC',
                'key' => Currency::YEC,
                'value' => $configs['YEC_VRT']['first_rmb'] ?? '0'
            ],
            [
                'unit' => 'rmb',
                'currency' => 'VRTS',
                'key' => Currency::VRTS,
                'value' => $configs['VRTS_ETH']['first_rmb'] ?? '0'
            ],
            [
                'unit' => 'rmb',
                'currency' => 'ETH',
                'key' => Currency::ETH,
                'value' => $configs['YEC_ETH']['second_rmb'] ?? '0'
            ]
        ];
        $to = [
            [
                'unit' => 'rmb',
                'currency' => 'VRT',
                'key' => Currency::VRT,
                'value' => $configs['YEC_VRT']['second_rmb'] ?? '0'
            ],
            [
                'unit' => 'rmb',
                'currency' => 'ETH',
                'key' => Currency::ETH,
                'value' => $configs['YEC_ETH']['second_rmb'] ?? '0'
            ],
            [
                'unit' => 'rmb',
                'currency' => 'VRTS',
                'key' => Currency::VRTS,
                'value' => $configs['VRTS_ETH']['first_rmb'] ?? '0'
            ]
        ];

        $data['to'] = $to;
        $data['from'] = $from;
        $data['YEC_VRT_RATIO'] = 5;
        $data['YEC_ETH'] = $configs['YEC_ETH']['exchange_value'] ?? '0';
        $data['VRTS_ETH'] = $configs['VRTS_ETH']['exchange_value'] ?? '0';
        $data['ETH_VRTS'] = $configs['ETH_VRTS']['exchange_value'] ?? '0';
        $data['YEC_VRT'] = $configs['YEC_VRT']['exchange_value'] * 5 ?? '0';
      	$data['YEC_VRTS'] = $configs['YEC_VRTS']['exchange_value'] ?? '0';

        return $this->success($data);
    }

    /**
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ConfigNotSetException
     */
    public function store(Request $request)
    {	
        $user = $this->getUser();
        $value = $user->{Currency::getStrByCode($request->from_currency)};

        if (abs($request->from_value) > $value) {
            return $this->fail(Code::PARAMETER_ERROR, '兑换金额不足');
        }

        $type = Str::upper(Currency::getStrByCode($request->from_currency)
            . '_' . Currency::getStrByCode($request->to_currency));

        $configs = Config::getExchanges();
        if (!array_has($configs, $type)) {
            return $this->fail(Code::PARAMETER_ERROR, '不支持的兑换规则');
        }
        $config = $configs[$type];
        $exchangeValue = (string) $config['exchange_value'];
        if ($type == 'YEC_VRT') {
            $exchangeValue = $exchangeValue * 5; // todo 5 倍的概念
        }
        $data = [
            'from_value' => big_number(abs($request->from_value)),
        ];
        $data['to_value'] = (clone $data['from_value'])->multiply($exchangeValue);

        $function = function () use ($request, $data) {
            $user = $this->getUser();
            $exchange = Exchange::create([
                'user_id' => $user->id,
                'to_value' => $data['to_value'],
                'to_currency' => $request->to_currency,
                'from_currency' => $request->from_currency,
                'from_value' => $data['from_value']->negate()
            ]);

            $from = [
                'user_id' => $user->id,
                'value' => $exchange->from_value,
                'currency' => $exchange->from_currency,
                'type' => '兑换至 ' . Str::upper(Currency::getStrByCode($exchange->to_currency)),
            ];

            $to = [
                'user_id' => $user->id,
                'value' => $exchange->to_value,
                'currency' => $exchange->to_currency,
                'type' => Str::upper(Currency::getStrByCode($exchange->from_currency)) . ' 兑换至',
            ];
            $exchange->records()->create($to);
            $exchange->records()->create($from);
        };
		
        try {
            DB::transaction($function);
        } catch (Throwable $exception) {
            return $this->fail(Code::SERVER_ERROR, '兑换失败');
        }
		
        return $this->success();
    }

    public function index(Request $request)
    {
        $query = Exchange::where('user_id', $this->getUser()->id);
        if ($request->type == 1) {
            $pagination = $query->where(function ($query) {
                    $query->where('to_currency', '!=', Currency::VRT)
                        ->orWhere('from_currency', '!=', Currency::VRTS);
                })->orderByDesc('created_at')->paginate();
        } else {
            $pagination = $query->where('from_currency', Currency::VRTS)
                ->where('to_currency', Currency::VRT)->orderByDesc('created_at')->paginate();
        }

        return $this->success(new ExchangeCollection($pagination));
    }
}
